package cn.yunhe.springmvc.file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Controller
public class UploadAction {

	@RequestMapping(value = "/index")
	public String uploadFile() {
		return "index";
	}

	/*
	 * 采用file.Transto 来保存上传的文件
	 */
	@RequestMapping("/upload")
	public String fileUpload2(@RequestParam("file") MultipartFile file) throws IOException {
		long startTime = System.currentTimeMillis();
		System.out.println("fileName：" + file.getOriginalFilename());
		String path = "C:/tools/" + new Date().getTime() + file.getOriginalFilename();

		File newFile = new File(path);
		// 通过CommonsMultipartFile的方法直接写文件（注意这个时候）
		file.transferTo(newFile);
		long endTime = System.currentTimeMillis();
		System.out.println("方法二的运行时间：" + String.valueOf(endTime - startTime) + "ms");
		return "success";
	}

	@RequestMapping(value = "/upload2")
	public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest req) throws IOException {
		// 获取文件存储位置
		String path = req.getSession().getServletContext().getRealPath("/fileupload");
		// 获取file的输入流
		InputStream is = file.getInputStream();
		// 创建文件的输出流
		OutputStream os = new FileOutputStream(new File(path, file.getOriginalFilename()));
		byte[] buffer = new byte[200];
		int len;
		while ((len = is.read(buffer)) != -1) {
			os.write(buffer, 0, len);
		}
		os.close();
		is.close();
		System.out.println("文件上传成功！");
		return "/index.jsp";
	}

}
